<template>
  <view class="my-tasks-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">我的任务</block>
    </cu-custom>

    <!-- 任务统计 -->
    <view class="task-stats margin-top bg-white">
      <view class="stats-grid padding">
        <view class="stat-item">
          <view class="stat-number text-blue">{{ taskStats.total }}</view>
          <view class="stat-label">总任务</view>
        </view>
        <view class="stat-item">
          <view class="stat-number text-green">{{ taskStats.completed }}</view>
          <view class="stat-label">已完成</view>
        </view>
        <view class="stat-item">
          <view class="stat-number text-orange">{{ taskStats.inProgress }}</view>
          <view class="stat-label">进行中</view>
        </view>
        <view class="stat-item">
          <view class="stat-number text-purple">{{ taskStats.pending }}</view>
          <view class="stat-label">待开始</view>
        </view>
      </view>
    </view>

    <!-- 筛选器 -->
    <view class="filter-bar margin-top bg-white padding">
      <view class="filter-tabs">
        <view v-for="tab in filterTabs" :key="tab.value"
              class="filter-tab" 
              :class="{ active: currentFilter === tab.value }"
              @click="changeFilter(tab.value)">
          {{ tab.label }}
        </view>
        <view class="filter-more" @click="openTaskFilterModal">
          <text class="cuIcon-filter text-blue"></text>
          <text class="filter-text">筛选</text>
        </view>
      </view>
    </view>

    <!-- 任务列表 -->
    <view class="task-list margin-top">
      <view v-for="task in filteredTasks" :key="task.id" 
            class="task-item bg-white margin-bottom" 
            @click="viewTaskDetail(task)">
        <view class="task-header padding">
          <view class="flex justify-between align-center">
            <view class="task-title">{{ task.title }}</view>
            <view class="task-status" :class="task.statusClass">
              {{ task.statusText }}
            </view>
          </view>
          <view class="task-info margin-top-sm">
            <text class="text-sm text-gray">工种：{{ task.workType }}</text>
            <text class="text-sm text-gray margin-left">计划：{{ task.planName }}</text>
          </view>
        </view>
        
        <view class="task-content padding-lr">
          <view class="task-progress margin-bottom-sm">
            <view class="flex justify-between align-center margin-bottom-xs">
              <text class="text-sm">进度</text>
              <text class="text-sm">{{ task.progress }}%</text>
            </view>
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: task.progress + '%' }"></view>
            </view>
          </view>
          
          <view class="task-meta flex justify-between text-sm text-gray">
            <text>开始时间：{{ formatTime(task.startTime) }}</text>
            <text>预计完成：{{ formatTime(task.expectedEndTime) }}</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="task-actions padding" v-if="task.status !== 'completed'">
          <view class="action-buttons flex gap-sm">
            <button v-if="task.status === 'pending'" 
                    class="cu-btn sm bg-blue" 
                    @click.stop="startTask(task)">
              开始任务
            </button>
            <button v-if="task.status === 'in_progress'" 
                    class="cu-btn sm bg-orange" 
                    @click.stop="pauseTask(task)">
              暂停
            </button>
            <button v-if="task.status === 'paused'" 
                    class="cu-btn sm bg-green" 
                    @click.stop="resumeTask(task)">
              继续
            </button>
            <button v-if="task.status === 'in_progress'" 
                    class="cu-btn sm bg-purple" 
                    @click.stop="updateProgress(task)">
              更新进度
            </button>
            <button v-if="task.progress >= 100 && task.status !== 'completed'" 
                    class="cu-btn sm bg-green" 
                    @click.stop="completeTask(task)">
              完成任务
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredTasks.length === 0" class="empty-state text-center padding">
      <text class="cuIcon-list text-gray" style="font-size: 120rpx;"></text>
      <view class="text-gray margin-top">暂无任务</view>
    </view>

    <!-- 任务筛选弹窗 -->
    <uni-popup ref="taskFilterPopup" type="bottom">
      <view class="filter-modal">
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
          <text class="cuIcon-close" @click="closeTaskFilterModal"></text>
        </view>
        
        <view class="filter-content">
          <!-- 任务状态筛选 -->
          <view class="filter-section">
            <view class="section-title">任务状态</view>
            <view class="checkbox-group">
              <view v-for="status in taskStatusOptions" :key="status.value"
                    class="checkbox-item"
                    :class="{ checked: taskFilter.statusList.includes(status.value) }"
                    @click="toggleTaskStatus(status.value)">
                <text class="checkbox-text">{{ status.label }}</text>
              </view>
            </view>
          </view>

          <!-- 工作类型筛选 -->
          <view class="filter-section">
            <view class="section-title">工作类型</view>
            <view class="checkbox-group">
              <view v-for="workType in workTypeOptions" :key="workType.id"
                    class="checkbox-item"
                    :class="{ checked: taskFilter.workTypeList.includes(workType.id) }"
                    @click="toggleWorkType(workType.id)">
                <text class="checkbox-text">{{ workType.typeName }}</text>
              </view>
            </view>
          </view>

          <!-- 时间范围筛选 -->
          <view class="filter-section">
            <view class="section-title">时间范围</view>
            <view class="time-range-options">
              <view v-for="option in timeRangeOptions" :key="option.value"
                    class="checkbox-item"
                    :class="{ checked: taskFilter.timeRange === option.value }"
                    @click="selectTimeRange(option.value)">
                <text class="checkbox-text">{{ option.label }}</text>
              </view>
            </view>
            
            <!-- 自定义时间选择 -->
            <view v-if="taskFilter.timeRange === 'custom'" class="custom-date-section">
              <view class="date-picker-row">
                <text class="date-label">开始时间：</text>
                <picker mode="date" :value="taskFilter.startDate" @change="onTaskStartDateChange">
                  <view class="date-picker">
                    {{ taskFilter.startDate || '请选择' }}
                  </view>
                </picker>
              </view>
              <view class="date-picker-row">
                <text class="date-label">结束时间：</text>
                <picker mode="date" :value="taskFilter.endDate" @change="onTaskEndDateChange">
                  <view class="date-picker">
                    {{ taskFilter.endDate || '请选择' }}
                  </view>
                </picker>
              </view>
            </view>
          </view>
        </view>
        
        <view class="filter-footer">
          <view class="filter-btn reset" @click="resetTaskFilter">重置</view>
          <view class="filter-btn confirm" @click="applyTaskFilter">确定</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import productionPlanV2 from '@/api/mes/productionPlanV2.js'
import authService from '@/common/auth/authService.js'

export default {
  data() {
    return {
      currentFilter: 'all',
      filterTabs: [
        { label: '全部', value: 'all' },
        { label: '已分配', value: 'assigned' },
        { label: '进行中', value: 'in_progress' },
        { label: '已暂停', value: 'paused' },
        { label: '已完成', value: 'completed' }
      ],
      taskStats: {
        total: 0,
        completed: 0,
        inProgress: 0,
        pending: 0
      },
      tasks: [],
      taskFilter: {
        statusList: [],
        workTypeList: [],
        timeRange: '',
        startDate: '',
        endDate: ''
      },
      taskStatusOptions: [
        { label: '待领取', value: 0 },
        { label: '已领取', value: 1 },
        { label: '进行中', value: 2 },
        { label: '已完成', value: 3 },
        { label: '暂停', value: 4 }
      ],
      workTypeOptions: [],
      timeRangeOptions: [
        { label: '今天', value: 'today' },
        { label: '本周', value: 'week' },
        { label: '本月', value: 'month' },
        { label: '最近3个月', value: 'quarter' },
        { label: '自定义', value: 'custom' }
      ]
    }
  },

  computed: {
    filteredTasks() {
      if (this.currentFilter === 'all') {
        return this.tasks
      }
      return this.tasks.filter(task => task.status === this.currentFilter)
    }
  },

  onLoad() {
    this.loadMyTasks()
    this.loadWorkTypes()
  },

  onPullDownRefresh() {
    this.loadMyTasks().then(() => {
      uni.stopPullDownRefresh()
    })
  },

  methods: {
    async loadMyTasks(filterParams = {}) {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const response = await productionPlanV2.getMyTasks(filterParams)
        this.tasks = response.data.map(task => ({
          ...task,
          statusClass: this.calculateStatusClass(task.status),
          statusText: this.calculateStatusText(task.status)
        }))
        
        this.calculateStats()
        
      } catch (error) {
        console.error('加载任务失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    calculateStats() {
      this.taskStats = {
        total: this.tasks.length,
        completed: this.tasks.filter(t => t.status === 'completed').length,
        inProgress: this.tasks.filter(t => t.status === 'in_progress').length,
        pending: this.tasks.filter(t => t.status === 'assigned' || t.status === 'pending').length
      }
    },

    calculateStatusClass(status) {
      const statusMap = {
        'pending': 'status-pending',
        'assigned': 'status-pending',
        'in_progress': 'status-progress',
        'paused': 'status-paused',
        'completed': 'status-completed',
        'cancelled': 'status-cancelled'
      }
      return statusMap[status] || 'status-pending'
    },

    calculateStatusText(status) {
      const statusMap = {
        'pending': '待领取',
        'assigned': '已分配',
        'in_progress': '进行中',
        'paused': '已暂停',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知'
    },

    changeFilter(filter) {
      this.currentFilter = filter
    },

    viewTaskDetail(task) {
      uni.navigateTo({
        url: `/pages/production/task/detail?id=${task.id}`
      })
    },

    async startTask(task) {
      if (!authService.hasPermission('production:task:start')) {
        uni.showToast({
          title: '无权限操作',
          icon: 'none'
        })
        return
      }
      
      try {
        await productionPlanV2.startTask(task.id)
        uni.showToast({
          title: '任务已开始',
          icon: 'success'
        })
        this.loadMyTasks()
      } catch (error) {
        console.error('开始任务失败:', error)
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },

    async pauseTask(task) {
      if (!authService.hasPermission('production:task:pause')) {
        uni.showToast({
          title: '无权限操作',
          icon: 'none'
        })
        return
      }
      
      try {
        await productionPlanV2.pauseTask(task.id)
        uni.showToast({
          title: '任务已暂停',
          icon: 'success'
        })
        this.loadMyTasks()
      } catch (error) {
        console.error('暂停任务失败:', error)
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },

    async resumeTask(task) {
      if (!authService.hasPermission('production:task:resume')) {
        uni.showToast({
          title: '无权限操作',
          icon: 'none'
        })
        return
      }
      
      try {
        await productionPlanV2.resumeTask(task.id)
        uni.showToast({
          title: '任务已恢复',
          icon: 'success'
        })
        this.loadMyTasks()
      } catch (error) {
        console.error('恢复任务失败:', error)
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },

    updateProgress(task) {
      if (!authService.hasPermission('production:progress:update')) {
        uni.showToast({
          title: '无权限操作',
          icon: 'none'
        })
        return
      }
      
      uni.navigateTo({
        url: `/pages/production/task/detail?id=${task.id}`
      })
    },

    async completeTask(task) {
      if (!authService.hasPermission('production:task:complete')) {
        uni.showToast({
          title: '无权限操作',
          icon: 'none'
        })
        return
      }
      
      uni.showModal({
        title: '确认完成',
        content: `确定要完成任务 ${task.title} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await productionPlanV2.completeTask(task.id, { 
                actualQuantity: task.planQuantity || task.plannedQuantity,
                qualityLevel: 'A',
                remark: '任务完成'
              })
              uni.showToast({
                title: '任务已完成',
                icon: 'success'
              })
              this.loadMyTasks()
            } catch (error) {
              console.error('完成任务失败:', error)
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    formatTime(timeStr) {
      if (!timeStr) return '--'
      const date = new Date(timeStr)
      return `${date.getMonth() + 1}/${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },

    // 任务筛选相关方法
    async loadWorkTypes() {
      try {
        const response = await this.$http.get('/mes/worktype/all')
        if (response.success) {
          this.workTypeOptions = response.result || []
        }
      } catch (error) {
        console.error('加载工作类型失败:', error)
      }
    },

    openTaskFilterModal() {
      this.$refs.taskFilterPopup.open()
    },

    closeTaskFilterModal() {
      this.$refs.taskFilterPopup.close()
    },

    toggleTaskStatus(status) {
      const index = this.taskFilter.statusList.indexOf(status)
      if (index > -1) {
        this.taskFilter.statusList.splice(index, 1)
      } else {
        this.taskFilter.statusList.push(status)
      }
    },

    toggleWorkType(workTypeId) {
      const index = this.taskFilter.workTypeList.indexOf(workTypeId)
      if (index > -1) {
        this.taskFilter.workTypeList.splice(index, 1)
      } else {
        this.taskFilter.workTypeList.push(workTypeId)
      }
    },

    selectTimeRange(range) {
      this.taskFilter.timeRange = range
      if (range !== 'custom') {
        this.taskFilter.startDate = ''
        this.taskFilter.endDate = ''
      }
    },

    onTaskStartDateChange(e) {
      this.taskFilter.startDate = e.detail.value
    },

    onTaskEndDateChange(e) {
      this.taskFilter.endDate = e.detail.value
    },

    resetTaskFilter() {
      this.taskFilter = {
        statusList: [],
        workTypeList: [],
        timeRange: '',
        startDate: '',
        endDate: ''
      }
    },

    applyTaskFilter() {
      // 构建查询参数
      const params = {}
      
      // 任务状态筛选
      if (this.taskFilter.statusList.length > 0) {
        params.status_in = this.taskFilter.statusList.join(',')
      }
      
      // 工作类型筛选
      if (this.taskFilter.workTypeList.length > 0) {
        params.workTypeId_in = this.taskFilter.workTypeList.join(',')
      }
      
      // 时间范围筛选
      if (this.taskFilter.timeRange) {
        const now = new Date()
        let startDate, endDate
        
        switch (this.taskFilter.timeRange) {
          case 'today':
            startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
            endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)
            break
          case 'week':
            const weekStart = new Date(now.getTime() - (now.getDay() * 24 * 60 * 60 * 1000))
            startDate = new Date(weekStart.getFullYear(), weekStart.getMonth(), weekStart.getDate())
            endDate = new Date(startDate.getTime() + (7 * 24 * 60 * 60 * 1000))
            break
          case 'month':
            startDate = new Date(now.getFullYear(), now.getMonth(), 1)
            endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1)
            break
          case 'quarter':
            startDate = new Date(now.getTime() - (90 * 24 * 60 * 60 * 1000))
            endDate = now
            break
          case 'custom':
            if (this.taskFilter.startDate) {
              startDate = new Date(this.taskFilter.startDate)
            }
            if (this.taskFilter.endDate) {
              endDate = new Date(this.taskFilter.endDate)
              endDate.setDate(endDate.getDate() + 1) // 包含结束日期
            }
            break
        }
        
        if (startDate) {
          params.createTime_begin = startDate.toISOString().split('T')[0]
        }
        if (endDate) {
          params.createTime_end = endDate.toISOString().split('T')[0]
        }
      }
      
      // 应用筛选并重新加载数据
      this.loadMyTasks(params)
      this.closeTaskFilterModal()
    }
  }
}
</script>

<style lang="scss" scoped>
.my-tasks-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.task-stats {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24rpx;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.filter-bar {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .filter-tabs {
    display: flex;
    align-items: center;
    
    .filter-tab {
      flex: 1;
      text-align: center;
      padding: 16rpx 8rpx;
      font-size: 28rpx;
      color: #666;
      border-bottom: 4rpx solid transparent;
      
      &.active {
        color: #1890ff;
        border-bottom-color: #1890ff;
        font-weight: bold;
      }
    }
    
    .filter-more {
      display: flex;
      align-items: center;
      padding: 16rpx;
      gap: 8rpx;
      
      .filter-text {
        font-size: 28rpx;
        color: #1890ff;
      }
    }
  }
}

.task-list {
  margin: 0 24rpx;
  
  .task-item {
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    
    .task-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .task-status {
      padding: 8rpx 16rpx;
      border-radius: 16rpx;
      font-size: 24rpx;
      
      &.status-pending {
        background-color: #fff7e6;
        color: #fa8c16;
      }
      
      &.status-progress {
        background-color: #e6f7ff;
        color: #1890ff;
      }
      
      &.status-paused {
        background-color: #fff1f0;
        color: #f5222d;
      }
      
      &.status-completed {
        background-color: #f6ffed;
        color: #52c41a;
      }
    }
    
    .progress-bar {
      height: 8rpx;
      background-color: #f0f0f0;
      border-radius: 4rpx;
      overflow: hidden;
      
      .progress-fill {
        height: 100%;
        background-color: #1890ff;
        transition: width 0.3s ease;
      }
    }
    
    .action-buttons {
      .cu-btn {
        flex: 1;
        margin-right: 16rpx;
        
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
}

.empty-state {
  margin-top: 120rpx;
}

// 任务筛选弹窗样式
.filter-modal {
  background: white;
  border-radius: 24rpx 24rpx 0 0;
  max-height: 80vh;
  overflow: hidden;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx;
  border-bottom: 1px solid #f0f0f0;
}

.filter-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.filter-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 40rpx;
}

.filter-section {
  margin: 40rpx 0;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 24rpx;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.time-range-options {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.checkbox-item {
  padding: 16rpx 32rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 40rpx;
  background: #f8f8f8;
  transition: all 0.3s;
}

.checkbox-item.checked {
  border-color: #007aff;
  background: #e3f2fd;
}

.checkbox-text {
  font-size: 28rpx;
  color: #666;
}

.checkbox-item.checked .checkbox-text {
  color: #007aff;
}

.custom-date-section {
  margin-top: 24rpx;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.date-picker-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.date-picker-row:last-child {
  margin-bottom: 0;
}

.date-label {
  font-size: 28rpx;
  color: #666;
  width: 160rpx;
}

.date-picker {
  flex: 1;
  padding: 16rpx 24rpx;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
}

.filter-footer {
  display: flex;
  padding: 30rpx 40rpx;
  border-top: 1px solid #f0f0f0;
  gap: 20rpx;
}

.filter-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 32rpx;
}

.filter-btn.reset {
  background: #f0f0f0;
  color: #666;
}

.filter-btn.confirm {
  background: #007aff;
  color: white;
}
</style>
